//
//  TextDocumentViewController.m
//  ExhibitForcePrototype
//
//  Created by Dilyana Todorova on 12/5/12.
//  Copyright (c) 2012 Dilyana Todorova. All rights reserved.
//

#import "TextDocumentViewController.h"

@interface TextDocumentViewController ()
@property(nonatomic, weak) IBOutlet UIWebView * documentViewer;
@end

@implementation TextDocumentViewController
@synthesize fileName = _fileName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _fileName = @"Example";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSString * filePath = [[NSBundle mainBundle] pathForResource:self.fileName ofType:@"pdf"];
    self.title = self.fileName;
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(dismissView:)];
    UIBarButtonItem * addToCardBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addToCard:)];
    self.navigationItem.leftBarButtonItem = doneButton;
    self.navigationItem.rightBarButtonItem = addToCardBarButtonItem;
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]){
        NSURL * fileURL = [NSURL fileURLWithPath:filePath];
        NSURLRequest * request = [NSURLRequest requestWithURL:fileURL];
        [self.documentViewer loadRequest:request];

    } else {
        UIAlertView * erroMessage = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"There is no such pdf file" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [erroMessage show];
    }
    
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

#pragma mark - web view delegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

#pragma mark - low memmory notification
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    self.documentViewer = nil;
}

#pragma mark - actions

- (IBAction)addToCard:(id)sender {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Added to card" message:@"You added the document to card" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

- (void) dismissView :(UIBarButtonItem *)sender{
    [self.delegate didDismissDetailView];
}
@end
